// pages/select-details/select-detailst.js
var jsonData = require('../../data/new.js');
import {
  client
} from "../../utils/request.js"
var {
  throttle,
  debounce
} = require('../../utils/tools');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: 0,
    classRoom: {},
    seatLsit: [],
    deckList: [],
    shelfList: [],
    seatTypeList: [],
    seatInit: [],
    seatStatusData: [],
    seatId: 0,
    seatSatus: false,
    seatInfoToShow: {},
    // 时间控件开始
    isPickerRender: false,
    isPickerShow: true,
  },

  onShow: function () {
    wx.showLoading({
      title: '加载中',
    })


    var that = this;
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过sleset传送到当前页面的数据
    const eventChannel = that.getOpenerEventChannel()
    eventChannel.on('acceptDataFromOpenerPage', function (data) {
      that.setData({
        classRoom: {
          class_id: data.class_id,
          class_name: data.class_name,
          now_time: data.now_time
        }
      })
    })
    //---这此替换成自己的接口请求成功后--start--
    //从缓存获取座位信息
    wx.getStorage({
      key: 'data',
      success(data) {
        let class_id = that.data.classRoom.class_id
        let now_time = that.data.classRoom.now_time
        //给插槽的时间
        let postStartTime = now_time.split(":")
        let postEndTime = postStartTime[1].toString().split("-")
        let res = jsonData.dataList;

        //产生 9,10,11,12,13
        let ss = parseInt(postStartTime[0])
        let ee = parseInt(postEndTime[1])
        let postArr = []
        for (let i = ss; i <= ee; i++) {
          postArr.push(i)
        }
        let postTiemToString = postArr.toString()


        // 座位
        let seatInit = data.data.data.seat[class_id]
      //桌子 书架
         let deskInit =data.data.data.desk[class_id]
         let bookshelfInit = data.data.data.bookshelf[class_id]
       
        client({
          url: '/seatInfo/getRoomInfoByTimeSlot?schoolName=HR&room=' + class_id + '&timeSlot=' + postTiemToString
        }).then(data => {
          let seatStatusData = data.data
          //合并状态
          let result = seatInit.map((item, index) => {
            item.type = seatStatusData[index].flag
            return item
          })       
          let seatList = that.defaultSeat(result, res.seatTypeList);
          that.setData({
            seatList: seatList,
            /*
            桌子  书架预留位置
            */
           deckList:deskInit,
           shelfList:bookshelfInit,
            seatInit: seatInit,
            seatStatusData: seatStatusData,
            seatTypeList: res.seatTypeList,
          })
        }).catch(err => {
          console.log(err)
        })
      }
    })
    wx.hideLoading();
  },
  // 获得当前时间
  bindPickerTime: function (e) {
  
    this.setData({
      index: e.detail.value
    })
  },

  // 位置处理
  defaultSeat: function (seatList, seatType) {
    let response = {
      seatList,
      seatType
    }
    let resSeatList = response.seatList
    resSeatList.forEach(element => {
      // // 加载座位的图标
      let seatType = response.seatType;
      for (const key in seatType) {
        // 加载每个座位的初始图标defautIcon 和 当前图标 nowIcon
        if (element.type === seatType[key].type) {
          element.nowIcon = seatType[key].icon
          // 加个背景颜色属性
          element.backgroundDefaut = "rgb(235, 57, 65)"
          element.defautIcon = seatType[key].icon
        } else
          // 根据首字母找到对应的被选中图标
          if (false === seatType[key].type) {
            element.selectedIcon = seatType[key].icon
            element.backgroundDefaut = "rgb(219, 219, 219)"
          }
      }
    })
    return resSeatList
  },
  // 改变选中状态
  clickSeat: throttle(function (e) {
    let that = this
    //从setdata里面拿
    // 直接拿则变成了多选 
    // let seatList = that.data.seatList;

    // 这个方法消耗一点性能
    let seatTypeList = that.data.seatTypeList
    let seatInit = that.data.seatInit
    let seatStatusData = that.data.seatStatusData
    let res = seatInit.map((item, index) => {
      item.type = seatStatusData[index].flag
      return item
    })
    let seatList = that.defaultSeat(res, seatTypeList)

    // 用户信息
    let seatInfo = e.currentTarget.dataset
    let seatDetail = e.currentTarget.dataset.index

    if (seatInfo.index.type === true) {
      //选择了座位后可以干的事
      seatInfo.index.backgroundDefaut = " rgb(0, 178, 106)"
      const userInfo = wx.getStorageSync('userInfo')

      //座位信息保存
      that.setData({
        seatInfoToShow: {
          id: this.data.seatList[seatInfo.id].id,
          show: true
        }
      })

      //如果重新选择的座位id和原来id相同则改变图标
      let fristId = this.data.seatList[seatInfo.id].id
      if (this.data.seatId === fristId) {
        if (!this.data.seatStatus) {
          seatList[seatInfo.id].nowIcon = seatDetail.defautIcon
          seatList[seatInfo.id].backgroundDefaut = "rgb(219, 219, 219)"
          that.setData({
            seatList: seatList,
            seatStatus: true,
            seatInfoToShow: {
              show: false
            }
          })
        } else {
          seatList[seatInfo.id].nowIcon = seatDetail.selectedIcon
          seatList[seatInfo.id].backgroundDefaut = seatDetail.backgroundDefaut
          // seatDetail.nowIcon=seatDetail.selectedIcon
          that.setData({
            seatList: seatList,
            seatStatus: false
          })
        }
      } else {
        seatList[seatInfo.id].nowIcon = seatDetail.selectedIcon
        seatList[seatInfo.id].backgroundDefaut = seatDetail.backgroundDefaut

        // seatDetail.nowIcon=seatDetail.selectedIcon
        that.setData({
          seatList: seatList,
          seatId: fristId
        })
      }
    } else {
      wx.showToast({
        title: '位置已被选',
        icon: 'none',
        duration: 1000
      })
      return
    }
    return
  }, 500),

  //关闭底部选择 同步座位信息
  colseSeat: function (e) {
    let that = this
    that.setData({
      seatInfoToShow: {
        seatStatus: false,
        show: false
      }
    })
  },

  //确认选座事件
  submitSeat: function (e) {
    let class_id = e.currentTarget.dataset.classid
    // 楼层号
    let floor_id = class_id.split("")[1]
  
    let class_name = e.currentTarget.dataset.classname

    let seatId = e.currentTarget.dataset.id
    const userInfo = wx.getStorageSync('userInfo')
    let username = userInfo.username
    let address = userInfo.address
    let that = this
    let now_time = that.data.classRoom.now_time

    let time = now_time.split("-")
    let startTime = time[0].toString().split(":00")
    let endTime = time[1].toString().split(":00")
    let ss = parseInt(startTime[0])
    let ee = parseInt(endTime[0])
    let postArr = []
    for (let i = ss; i <= ee; i++) {
      postArr.push(i)
    }
    let timeSlot = postArr.toString()
    let schoolName = 'HR'

     if(seatId){
      client({
        url: 'seatInfo/reserveSeat',
        method: "post",
        data: {
          username,
          seatId,
          schoolName,
          timeSlot,
          address
        }
      }).then(data => {
        // console.log(data);
        if (data.data.flag) {
          wx.showLoading({
            title: '选座成功',
            success() {
              wx.reLaunch({
                url: '../index/index',
              })
            }
          })
          setTimeout(function () {
            wx.hideLoading()
          }, 1000)
        } else {
          wx.showToast({
            title: data.data.msg,
            icon: 'none',
            duration: 2000
          })
          
         
          setTimeout(function () {
            wx.hideLoading()
          }, 1000)
        }
  
        
      }).catch(err => {
        console.log(err)
      })
     }else{
      wx.showToast({
        title: '请确认是否选中座位',
        icon: 'none',
        duration: 2000
      })
     }
  
  },

  //组件通信
  _pickerHide(e) {
    this.setData({
      isPickerShow: !e.detail.pickerShow,
      isPickerRender: false,
    });
  },
  //得到开始时间和结束时间  重新渲染
  confirmTime(e) {
    let that = this
    let class_name = that.data.classRoom.class_name
    let class_id = that.data.classRoom.class_id

    //给插槽的时间
    let startTime = e.detail.startTime.toString()
    let endTime = e.detail.endTime.toString()
    //给请求的时间
    let postStartTime = startTime.split(":")
    let postEndTime = endTime.split(":")

    //产生 9,10,11,12,13
    let ss = parseInt(postStartTime[0])
    let ee = parseInt(postEndTime[0])
    let postArr = []
    for (let i = ss; i <= ee; i++) {
      postArr.push(i)
    }
    let postTiemToString = postArr.toString()

    client({
      url: '/seatInfo/getRoomInfoByTimeSlot?schoolName=HR&room=' + class_id + '&timeSlot=' + postTiemToString
    }).then(data => {
      let seatStatusData = data.data
      //合并状态
      let seatInit = that.data.seatInit
      let seatTypeList = that.data.seatTypeList
      let result = seatInit.map((item, index) => {
        item.type = seatStatusData[index].flag
        return item
      })
      let seatList = that.defaultSeat(result, seatTypeList);
      that.setData({
        seatList: seatList,
        seatStatusData: seatStatusData,
        classRoom: {
          now_time: startTime + '-' + endTime,
          class_name: class_name,
          class_id: class_id
        }
      })
    }).catch(err => {
      console.log(err)
    })

  },

  //时间选择控件
  test: function (e) {
    this.setData({
      isPickerShow: false,
      isPickerRender: false,
    });
  },

})